import router from '@/router'
import { useUserStore } from '@/stores'
import axios, { AxiosError, type Method } from 'axios'
// import { showToast } from 'vant'

const instance = axios.create({
  baseURL: 'http://toutiao.itheima.net/v1_0/',
  timeout: 5000
})

const store = useUserStore()
instance.interceptors.request.use(
  (config) => {
    if (store.user?.token && config.headers)
      config.headers.Authorization = `Bearer ${store.user?.token}`
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    // if (res.data.message !== 'OK') {
    //   showToast(res.data.message || '业务失败')
    //   return Promise.reject(res.data)
    // }
    return res.data
  },
  (err: AxiosError) => {
    if (err.response?.status === 401) {
      store.delUser()
      router.push({
        path: '/login',
        query: { returnUrl: router.currentRoute.value.fullPath }
      })
    }
    return Promise.reject(err)
  }
)

// export default instance

type Data<T> = {
  data: T
  message: string
}
export const request = <T>(
  url: string,
  method: Method = 'GET',
  submitData?: object
) => {
  return instance.request<any, Data<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData
  })
}
